package shuaige.jdk.多线程.concurrent.completableFuture;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class 链式调用 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        链式调用 yibu = new 链式调用();
        yibu.链式调用();
    }

    public void 链式调用() {
        CompletableFuture<Void> f = CompletableFuture.supplyAsync(() -> {
                    //测试抛异常后,handle()方法接受并处理
                    int x = 1 / 0;
                    return "这是一个栗子";
                }).handle((res, ex) -> {
                    System.out.println("handle res = " + res);
                    if (Objects.nonNull(ex)) {
                        System.out.println("handle ex" + ex.getCause().getMessage());
                    }
                    return Objects.nonNull(ex) ? 0 : 1;
                    // 接收参数，然后返回
                }).thenApply(res -> {
                    System.out.println("thenApply res = " + res);
                    return res == 1 ? "success" : "error";
                    // 接收参数，但不返回
                }).thenAccept(res -> System.out.println("thenAccept res = " + res)
                )
                //
                .thenRun(() -> System.out.println("没有参数, 异步执行一个没有返回值的任务"));
        f.join();
    }

    public String get() {
        delay();
        return "异步任务结果";
    }

    public void delay() {
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
